import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:sp_util/sp_util.dart';
import 'package:yp/Xwidgets/navigation_bar.dart';
import 'package:yp/config/config.dart';
import 'package:yp/helper.dart';
import 'package:yp/pages/mall_app/my_gas/view.dart';
import 'package:yp/services/api.dart';
import 'package:yp/utils/util.dart';

class CoinDetail extends StatefulWidget {
  const CoinDetail({Key key}) : super(key: key);

  @override
  _CoinDetailState createState() => _CoinDetailState();
}

class _CoinDetailState extends State<CoinDetail> {
  Map cardinfo;

  String gasCode = '';
  String score = '';

  getInfo() {
    // 获取优惠券信息
    var params = {
      'access_token': SpUtil.getString('token'),
      'series': Get.arguments['coupon_rule_id'],
    };
    Api.cardmeidacouponruleget(params).listen((event) {
      if (event['code'] == 0) {
        setState(() {
          cardinfo = event;
        });
      }
    });
  }

  @override
  void initState() {
    getInfo();
    super.initState();
    score = Get.arguments['score'];
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Scaffold(
        appBar: YPXNavigationBar('兑换详情'),
        body: cardinfo != null
            ? Stack(
                children: [
                  Column(
                    children: [infoHead(), cardInfo(), cardcondition()],
                  ),
                  Positioned(
                    //方法二
                    bottom: 0,
                    child: bottomPay(),
                  )
                ],
              )
            : Container(),
      ),
    );
  }

  ///底部支付按钮
  Widget bottomPay() {
    // num store = state.goodsDetail != null &&
    //         state.goodsDetail['spec_item_detail'] != null
    //     ? state.goodsDetail['spec_item_detail']['store']
    //     : 0;
    return Container(
      color: Colors.white,
      width: 750.w,
      height: 150.w,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          GestureDetector(
            onTap: () async {
              var couponType = int.tryParse('${cardinfo['coupontype']}');
              if (couponType == 7 && gasCode.length < 1) {
                var result = await Get.to(MyGasPage(),
                    arguments: {'from': 'point_exchange'});
                print('result: $result');
                gasCode = result['gasCode'];
              } else {
                var params = {
                  "data_sign": 0,
                  "channel_num_id": 98,
                  "use_platform": 3,
                  "usr_num_id": SpUtil.getInt('empeNumId'),
                  "integral_exchange_count": score,
                  "coupon_rule_id": cardinfo['series'],
                  'access_token': SpUtil.getString('token'),
                  'sub_unit_num_id':
                      SpUtil.getObject(Config.GET_SHOP_INFO)['shop_id'],
                  "coupontype": couponType,
                  'gas_code': gasCode
                };
                if (couponType == 7) {
                  params['gas_code'] = gasCode;
                }
                // print('=============> params: $params');
                int a1 = DateTime.now().microsecondsSinceEpoch;
                print('开始请求接口:$a1');

                // return;
                Api.appexchange(params).listen((event) {
                  if (event['code'] == 0) {
                    int a2 = DateTime.now().microsecondsSinceEpoch;
                    print('=============> 接口请求: ${a2 - a1}');
                    gasCode = '';
                  } else {
                    toast(event['message']);
                    gasCode = '';
                  }
                });
                // Get.back();

                toast('兑换成功');
              }
            },
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 8),
              width: 600.w,
              height: 100.w,
              margin: EdgeInsets.only(right: 8),
              alignment: Alignment.center,
              decoration: BoxDecoration(
                color: Color(0xFFEA5504),
                borderRadius: BorderRadius.all(
                  Radius.circular(19),
                ),
              ),
              child: Text(
                '立即兑换',
                style: TextStyle(
                  fontSize: 14,
                  color: Colors.white,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget infoHead() {
    return Container(
      color: Colors.white,
      padding: EdgeInsets.all(20.w),
      child: Column(
        children: [
          Container(
            padding: EdgeInsets.all(15.w),
            height: 300.w,
            decoration: new BoxDecoration(
              color: Colors.white,
              borderRadius: new BorderRadius.all(new Radius.circular(20.0)),
              image: new DecorationImage(
                image: new AssetImage('assets/images/integral_couponbg.png'),
                //这里是从assets静态文件中获取的，也可以new NetworkImage(）从网络上获取
                centerSlice: new Rect.fromLTRB(270.0, 180.0, 1360.0, 730.0),
              ),
            ),
            child: Row(
              children: [
                Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.end,
                      children: [
                        // Text(
                        //   '￥',
                        //   style:
                        //       TextStyle(fontSize: 32.sp, color: Colors.white),
                        //   maxLines: 1,
                        //   overflow: TextOverflow.ellipsis,
                        // ),
                        // Text(
                        //   cardinfo['face_value'].toString(),
                        //   style:
                        //       TextStyle(fontSize: 50.sp, color: Colors.white),
                        //   maxLines: 1,
                        //   overflow: TextOverflow.ellipsis,
                        // )
                      ],
                    ),
                    // SizedBox(
                    //   height: 20.w,
                    // ),
                    Text(
                      '仅剩${cardinfo['stock_qty'].toString()}张',
                      style: TextStyle(fontSize: 32.sp, color: Colors.white),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    )
                  ],
                ),
                SizedBox(
                  width: 40.w,
                ),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text(
                        cardinfo['title'].toString(),
                        style: TextStyle(fontSize: 32.sp, color: Colors.white),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                      SizedBox(
                        height: 20.w,
                      ),
                      Text(
                        cardinfo['least_cost'] == 0
                            ? '无门槛限制'
                            : '门槛:${cardinfo['least_cost'].toString()}',
                        style: TextStyle(fontSize: 32.sp, color: Colors.white),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                      SizedBox(
                        height: 20.w,
                      ),
                      cardinfo['use_begin_date'] != null
                          ? Text(
                              '有效期:${getyearDayFromTimestamp(cardinfo['use_begin_date'])}至${getyearDayFromTimestamp(cardinfo['use_begin_end'])}',
                              style: TextStyle(
                                  fontSize: 28.sp, color: Colors.white),
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                            )
                          : Container()
                    ],
                  ),
                )
              ],
            ),
          )
        ],
      ),
    );
  }

  Widget cardInfo() {
    return Container(
      padding: EdgeInsets.all(40.w),
      color: Colors.white,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '$score积分',
            style: TextStyle(color: Colors.orange),
          ),
          SizedBox(
            height: 15.w,
          ),
          Row(
            children: [
              Text(cardinfo['title'].toString(),
                  style: TextStyle(fontSize: 36.sp)),
              SizedBox(
                width: 15.w,
              ),
              Text(
                  cardinfo['least_cost'] == 0
                      ? '无门槛'
                      : '门槛:${cardinfo['least_cost'].toString()}',
                  style: TextStyle(fontSize: 36.sp)),
            ],
          ),
          SizedBox(
            height: 15.w,
          ),
          Text(
            '开始时间:${getyearDayFromTimestamp(cardinfo['create_dtme'])}',
            style: TextStyle(color: Colors.grey, fontSize: 28.sp),
          ),
          SizedBox(
            height: 15.w,
          ),
          Text(
            '结束时间${getyearDayFromTimestamp(cardinfo['last_updtme'])}',
            style: TextStyle(color: Colors.grey, fontSize: 28.sp),
          ),
          SizedBox(
            height: 15.w,
          ),
          Text(
            '每人总领取量:${cardinfo['limit_usr_number'].toString()}',
            style: TextStyle(color: Colors.grey, fontSize: 28.sp),
          ),
        ],
      ),
    );
  }

  Widget cardcondition() {
    return Container(
      padding: EdgeInsets.all(40.w),
      color: Colors.white,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '券使用范围',
            style: TextStyle(fontSize: 36.sp),
          ),
          SizedBox(
            height: 30.w,
          ),
          Row(
            children: [
              Text('适用店铺:',
                  style: TextStyle(
                    fontSize: 28.sp,
                    color: Colors.grey,
                  )),
              SizedBox(
                width: 5.w,
              ),
              Text('全部店铺',
                  style: TextStyle(fontSize: 28.sp, color: Colors.grey)),
            ],
          ),
          Text('适用渠道:${cardinfo['applicable_platform_simplified']}',
              style: TextStyle(fontSize: 28.sp, color: Colors.grey)),
          SizedBox(
            height: 30.w,
          ),
          Text(
            '兑换说明',
            style: TextStyle(fontSize: 36.sp),
          ),
          SizedBox(
            height: 15.w,
          ),
          // Text(
          //   '结束时间',
          //   style: TextStyle(color: Colors.grey, fontSize: 28.sp),
          // ),
          SizedBox(
            height: 15.w,
          ),
          Text(
            '积分一旦兑换不支持退回\n兑换兑换燃气金额成功，直接充值到用户自行绑定选择的燃气账户',
            style: TextStyle(color: Colors.grey, fontSize: 28.sp),
          ),
        ],
      ),
    );
  }
}
